<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    :root {
      --background-color: black;
    }
  </style>
</head>

<body>
  <zxl-button type="primary">this is a web component</zxl-button>
  <zxl-button>按钮2</zxl-button>
  <!-- template 不会展示到页面上面，不影响页面显示，可以使用模板 -->
  <template id="test-btn">
    <button class="my-button">
      <!-- 没有内容的时候会显示slot的内容 -->
      <slot>默认按钮</slot>
    </button>
  </template>

  <script>
    class MyButton extends HTMLElement {
      constructor() {
        super();
        // mode 是否允许js从外部访问根节点
        let shadow = this.attachShadow({
          mode: "open"
        });
        let buttonTemplate = document.getElementById('test-btn');
        let cloneTemplate = buttonTemplate.content.cloneNode(true);

        const style = document.createElement('style');

        const type = this.getAttribute('type') || 'default';

        console.log(type);

        const btnStyleObj = {
          primary: {
            background: '#409eff',
            color: '#fff',
          },
          default: {
            background: '#909399',
            color: '#fff'
          }
        }

        // css var css定义一个变量
        style.textContent = `
            .my-button {
              outline: none;
              border: none;
              border-radius: 4px;
              display: inline-block;
              padding: 5px 20px;
              background: var(--background-color, ${btnStyleObj[type].background});
              color: var(--text-color, ${btnStyleObj[type].color});
              cursor: pointer;
            }
          `;
        shadow.appendChild(style);
        shadow.appendChild(cloneTemplate);
      }
    }

    customElements.define('zxl-button', MyButton);
  </script>
</body>

</html>